﻿using System.Transactions;
using AutoMapper;
using MediatR;
using Provenance.Domain.Breed;
using Provenance.Domain.DeepProcess;
using Provenance.Domain.Product;
using Provenance.Domain.Slaughter;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.Breed;
using Provenance.Infra.Interfaces.DeepProcess;
using Provenance.Infra.Interfaces.Product;
using Provenance.Infra.Interfaces.Slaughter;
using Provenance.Write.Api.Application.Command.Product;

namespace Provenance.Write.Api.Application.CommandHandler.Product
{
    public class InsertProductInfoCommandHandler : IRequestHandler<InsertProductInfoCommand, ApiResult>
    {
        private readonly IProductInfoRepository _productInfoRepository;
        private readonly ILogger<InsertProductInfoCommandHandler> _logger;
        private readonly IMapper _mapper;
        private readonly QiniuUtils _qiniuUtils;
        private readonly IBreedingInfoRepository _breedingInfoRepository;
        private readonly IBreedEnterpriseRepository _breedEnterpriseRepository;
        private readonly ISlaughterInfoRepository  _slaughterInfoRepository;
        private readonly ISlaughterEnterpriseRepository _slaughterEnterpriseRepository;
        private readonly IDeepProcessInfoRepository _deepProcessInfoRepository;
        private readonly IRowMaterialRepository _rowMaterialRepository;
        private readonly IAuxiliaryMaterialRepository _auxiliaryMaterialRepository;
        private readonly IAdditiveRepository _additiveRepository;
        private readonly IPackagingMaterialRepository _packagingMaterialRepository;
        private readonly IDeepProcessEnterpriseRepository _deepProcessEnterpriseRepository;


        public InsertProductInfoCommandHandler(IProductInfoRepository productInfoRepository, ILogger<InsertProductInfoCommandHandler> logger, IMapper mapper, QiniuUtils qiniuUtils, IBreedingInfoRepository breedingInfoRepository, IBreedEnterpriseRepository breedEnterpriseRepository, ISlaughterInfoRepository slaughterInfoRepository, ISlaughterEnterpriseRepository slaughterEnterpriseRepository, IDeepProcessInfoRepository deepProcessInfoRepository, IRowMaterialRepository rowMaterialRepository, IAuxiliaryMaterialRepository auxiliaryMaterialRepository, IAdditiveRepository additiveRepository, IPackagingMaterialRepository packagingMaterialRepository, IDeepProcessEnterpriseRepository deepProcessEnterpriseRepository)
        {
            _productInfoRepository = productInfoRepository;
            _logger = logger;
            _mapper = mapper;
            _qiniuUtils = qiniuUtils;
            _breedingInfoRepository = breedingInfoRepository;
            _breedEnterpriseRepository = breedEnterpriseRepository;
            _slaughterInfoRepository = slaughterInfoRepository;
            _slaughterEnterpriseRepository = slaughterEnterpriseRepository;
            _deepProcessInfoRepository = deepProcessInfoRepository;
            _rowMaterialRepository = rowMaterialRepository;
            _auxiliaryMaterialRepository = auxiliaryMaterialRepository;
            _additiveRepository = additiveRepository;
            _packagingMaterialRepository = packagingMaterialRepository;
            _deepProcessEnterpriseRepository = deepProcessEnterpriseRepository;
        }
        public async Task<ApiResult> Handle(InsertProductInfoCommand request, CancellationToken cancellationToken)
        {
            try
            {
               using(var tran=new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    try
                    {
                        var obj = _mapper.Map<ProductInfo>(request);
                        await _productInfoRepository.InsertEntity(obj);
                        var list = await _productInfoRepository.GetAllAsync(x => !x.IsDeleted);
                        var lastobj = list.OrderByDescending(x => x.ProductInfoId).FirstOrDefault();
                        //添加初始值
                        await _breedingInfoRepository.InsertEntity(new BreedingInfo()
                        {
                            ProductInfoId = lastobj.ProductInfoId,
                            BreedType = "伊拉兔",
                            BreedSource = "采购",
                            BreedFeedDays = 90,
                            BreedBrand="大北兔",
                            BreedManager = "小陈",
                            BreedDate = DateTime.Now
                        });
                        await _breedEnterpriseRepository.InsertEntity(new   BreedEnterprise()
                        {
                            ProductInfoId = lastobj.ProductInfoId,
                            FormName = "四川锦祥养殖基地",
                            Manager = "X总",
                            InventoryNum = 3200
                        });
                        await _slaughterInfoRepository.InsertEntity(new SlaughterInfo()
                        {
                            ProductInfoId = lastobj.ProductInfoId,
                            Batch = lastobj.ProductBatch,
                            AverageWeight = 20,
                            FactoryTime = DateTime.Now,
                            SlaughterTime = DateTime.Now.AddDays(90),
                        });
                        await _slaughterEnterpriseRepository.InsertEntity(new SlaughterEnterprise()
                        {
                            ProductInfoId = lastobj.ProductInfoId,
                            EnterpriseName = "四川锦祥食品有限公司",
                            EnterpriseCreateTime = DateTime.Now.AddYears(-10),
                            EnterpriseAddress = "四川省巴中市通江县XXX",
                            EnterpriseIntroduction = "公司简介公司简介公司简介公司简介公司简介公司简介公司简介公司简介公司简介公司简介公司简介"
                        });
                        await _deepProcessInfoRepository.InsertEntity(new DeepProcessInfo()
                        {
                            ProductInfoId = lastobj.ProductInfoId,
                            DeepProcessGroup = "生产1组",
                            DeepProcessManager = "小陈"
                        });
                        await _rowMaterialRepository.InsertEntity(new RowMaterial()
                        {
                            ProductInfoId = lastobj.ProductInfoId,
                            RowMaterialBatch = lastobj.ProductBatch
                        });
                        await _auxiliaryMaterialRepository.InsertEntity(new AuxiliaryMaterial()
                        {
                            ProductInfoId = lastobj.ProductInfoId,
                            AuxiliaryBatch = lastobj.ProductBatch,
                        });
                        await _additiveRepository.InsertEntity(new Additive()
                        {
                            ProductInfoId = lastobj.ProductInfoId,
                            AdditiveBatch = lastobj.ProductBatch,
                        });
                        await _packagingMaterialRepository.InsertEntity(new PackagingMaterial()
                        {
                            ProductInfoId = lastobj.ProductInfoId,
                            PackagingMaterialBatch = lastobj.ProductBatch,
                        });
                        await _deepProcessEnterpriseRepository.InsertEntity(new DeepProcessEnterprise()
                        {
                            ProductInfoId = lastobj.ProductInfoId,
                            EnterpriseName="四川锦祥食品有限公司",
                            EnterpriseLicense="SC21305427680"
                        });

                        
                        tran.Complete();
                        return ApiResult.Success();
                    }
                    finally
                    {
                        tran.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("Error inserting product info:" + ex.Message);
                return ApiResult.Failure("Error inserting product info:" + ex.Message);
            }
        }
    }
}
